package pjkanri.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pjkanri.entity.Account;
import pjkanri.service.Authenticator;
import pjkanri.service.ServiceException;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
  
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// リクエスト・パラメーターの取得
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		
		String forwardPath = "_login.jsp";
		
		// 認証処理（Model）の委譲
		Account account = null;
		
		try {
			account = Authenticator.authenticate(name, password);
		} catch (ServiceException e) {
			throw new ServletException(e);
		}
		
		if(account != null ){ // 認証成功
			
			// セッション管理開始
			HttpSession session = request.getSession();
			// ログイン日時のセット
			account.setLoginDateTime(new Date());
			// セッション・オブジェクトにAccountオブジェクトをセット
			session.setAttribute("account", account);
			
			forwardPath = "index.jsp";
		} else { // 認証失敗
			request.setAttribute("errorMessage","Invalid email or password.");
		}
		
		// 転送処理
		request.getRequestDispatcher(forwardPath).forward(request, response);
		
	}

}
